﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using PServiceBus.Core.Runtime.Messages;
using PServiceBus.Core.Runtime.Extensions;

namespace PServiceBus.Core.Runtime.Transports {
    [Serializable]
    public class TransportMessage : IDisposable {

        public string TopicName { get; set; }
        public Dictionary<string, string> Headers { get; set; }

        public DateTime CreateDate { get; set; }
        public TimeSpan ExpiresIn { get; set; }

        public bool IsExpired {
            get { return DateTime.Now.Subtract(CreateDate).TotalDays >= ExpiresIn.TotalDays; }
        }

        public List<Dictionary<string, object>> Parameters { get; set; }
        public static TransportMessage Empty {
            get { return new TransportMessage() { TopicName = null, Parameters = null };}
        }
        public bool IsEmpty {
            get {
                if (_isDisposed) throw new ObjectDisposedException("TransportMessage");
                return TopicName == null && Parameters == null;
            }
        }

        public bool IsResequenceMessage {
            get {
                if (Headers == null) return false;
                return Headers.ContainsKey(Constants.ESB_GROUP_ID_KEY) &&
                    Headers.ContainsKey(Constants.ESB_SEQUENCE_ID_KEY);
            }
        }

        public void IncludeHeaderInMessages() {
            var encodedHeader = Headers.Translate();
            foreach (var param in Parameters)
                param[Constants.ESBTOPIC_HEADERS] = encodedHeader;
        }

        public ResequenceMessage ResequenceMessageFor(Guid topicID) {
            return new ResequenceMessage(this) { TopicID = topicID };
        }

        public void Delete() {
            Dispose();
        }

        #region IDisposable Members
        [MessageShark.MessageSharkIgnore]
        private bool _isDisposed;

        public void Dispose() {
            if (_isDisposed) return;
            Parameters = null;
            Headers = null;
            _isDisposed = true;
        }

        #endregion
    }
}
